<template>
  <div class="rx-scrollx">
    <slot></slot>
    <!--假装一个滚动条，固定在底部-->
    <div class="rx-scrollx-bar">
       <!-- 保持和需要滚动的区域宽度一致，从而实现滚动同步一致-->
      <div class="rx-scrollx-bar-content"></div>
       <!--end-->
    </div>
    <!--end-->
  </div>
</template>
<script>
import {scrollbarWidth} from '../../rxtools/src/brower/env';
import {getMinSize as getElmentMinSize} from '../../rxtools/src/brower/element'
export default {
  name: "rx-scrollx",
  mounted() {
    var el = this.$el,
      bar = el.querySelectorAll(".rx-scrollx-bar"),
      bar = bar[bar.length-1], //嵌套时，
      barContent = bar.querySelector(".rx-scrollx-bar-content"),
      scrollContent;

    //监听滚动条滚动事件，实现位移同步
    bar.addEventListener("scroll", function(e) {
      scrollContent.style.left = -this.scrollLeft+'px';
    });

    this.reset = function() {
      scrollContent=null;
      var scrollContents = el.querySelectorAll("[rx-scrollx]");
      for(let i=0;i<scrollContents.length;i++){
        if(scrollContents[i].clientHeight>0){
          scrollContent=scrollContents[i];
          break;
        }
      }

      var left = 0;
      if (scrollContent) {
        //还原原来的滚动位置
        left = bar.scrollLeft = -parseFloat(scrollContent.style.left || 0);
        //计算barContent宽度
        //有右边的滚动条
        var right = el.scrollHeight == el.clientHeight ? 0 : scrollbarWidth;
        bar.style.right = right;
        barContent.style.width =
         ( Number(scrollContent.getAttribute("rx-scrollx")) ||
          getElmentMinSize(scrollContent) + (left || 0) + 40).width+'px';
      } else {
        barContent.style.width = 0;
      }
    };
    this.reset();
  }
};
</script>

<style lang="scss">
.rx-scrollx {
  position: relative;
  width: 100%;
  height: 100%;
  overflow-x: hidden;
  overflow-y: auto;
  // 预留一点滚动条空间，动态计算太麻烦了
  padding-bottom: 10px;

  [rx-scrollx] {
    position: relative;
  }
}

.rx-scrollx-bar {
  position: absolute;
  top: auto;
  left: 0;
  right: 0;
  bottom: 0;
  overflow: auto;
  z-index: 1;
}

.rx-scrollx-bar-content {
  height: 1px;
}
</style>

